package com.jianguozh.difs.support.service.base.service.impl;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.jianguozh.difs.support.service.component.file.core.FileClientManager;
import com.jianguozh.difs.support.service.component.file.core.client.FileClient;
import com.jianguozh.difs.support.service.base.service.IFileService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;

/**
 * 文件服务实现
 *
 * @author hanrs
 * @email 4076130@qq.com
 * @since 2022/7/12 16:25
 */
@Service
public class FileServiceImpl implements IFileService {

    @Autowired
    FileClientManager fileClientManager;

    @Override
    @SneakyThrows
    public String createFile(String name, String path, byte[] content) {
        String type = FileTypeUtil.getType(new ByteArrayInputStream(content), name);
        if (StrUtil.isBlank(path)) {
            path = DigestUtil.md5Hex(content) + "." + type;
        }

        if (StrUtil.isBlank(name)) {
            name = path;
        }

        FileClient fileClient = fileClientManager.getFileClient();
        Assert.notNull(fileClient, "文件上传客户端未就绪,不能执行文件上传操作.");
        return fileClient.upload(content, path);
    }

    @Override
    public byte[] getFileContent(String path) throws Exception {
        FileClient client = fileClientManager.getFileClient();
        Assert.notNull(client, "客户端为空.");
        return client.getContent(path);
    }

}
